package com.yulang.springbootnetty.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yulang.springbootnetty.enums.MsgActionEnum;
import com.yulang.springbootnetty.mapper.UsersMapper;
import com.yulang.springbootnetty.pojo.ChatMsg;
import com.yulang.springbootnetty.pojo.FriendsRequest;
import com.yulang.springbootnetty.pojo.MyFriends;
import com.yulang.springbootnetty.pojo.Users;
import com.yulang.springbootnetty.service.ChatMsgService;
import com.yulang.springbootnetty.service.FriendsRequestService;
import com.yulang.springbootnetty.service.MyFriendsService;
import com.yulang.springbootnetty.service.UsersService;
import com.yulang.springbootnetty.utils.ChatMsgs;
import com.yulang.springbootnetty.utils.JsonUtils;
import com.yulang.springbootnetty.utils.MD5Utils;
import com.yulang.springbootnetty.vo.FriendRequestVO;
import com.yulang.springbootnetty.vo.MyFriendsVO;
import com.yulang.springbootnetty.webscoket.DataContent;
import com.yulang.springbootnetty.webscoket.UserChannelRel;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2020-06-20
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Autowired
    private FriendsRequestService friendsRequestService;

    @Autowired
    private Sid sid;

    @Autowired
    private UsersMapper mapper;

    @Autowired
    private MyFriendsService myFriendsService;

    @Autowired
    private ChatMsgService chatMsgService;

    @Override
    public boolean nameIsExits(String username) {
        QueryWrapper<Users> query = new QueryWrapper<>();
        query.eq(Users.USERNAME,username);
        Users user = mapper.selectOne(query);
        if(user!=null){
            return true;
        }
        return false;
    }

    @Override
    public Users queryUserForLogin(String username, String password) {
        QueryWrapper<Users> query = new QueryWrapper<>();
        query.eq(Users.USERNAME,username);
        query.eq(Users.PASSWORD,password);
        return mapper.selectOne(query);
    }

    @Override
    public Users saveUser(Users users) throws Exception {
        users.setNickname(users.getUsername());
        users.setId(sid.nextShort());
        users.setFaceImage("");
        users.setFaceImageBig("");
        users.setQrcode("");
        users.setPassword(MD5Utils.getMD5Str(users.getPassword()));
        this.save(users);
        return users;
    }


    @Override
    public void addFriend(String myUserId, String friendId) {
        FriendsRequest entity = new FriendsRequest();
        entity.setId(sid.nextShort());
        entity.setSendUserId(myUserId);
        entity.setAcceptUserId(friendId);
        entity.setRequestDateTime(new Date());
        friendsRequestService.save(entity);
    }

    @Override
    public List<FriendRequestVO> friendRequest(String acceptUserId) {

        QueryWrapper<FriendsRequest> query = new QueryWrapper<>();
        query.eq(FriendsRequest.ACCEPT_USER_ID,acceptUserId);
        List<FriendsRequest> list = friendsRequestService.list(query);
        List<FriendRequestVO> result = new ArrayList<>();
        list.forEach(item->{
            Users sender = this.getById(item.getSendUserId());
            FriendRequestVO friendRequestVO = new FriendRequestVO();
            friendRequestVO.setSendFaceImage(sender.getFaceImage());
            friendRequestVO.setSendNickname(sender.getNickname());
            friendRequestVO.setSendUserId(sender.getId());
            friendRequestVO.setSendUsername(sender.getUsername());
            result.add(friendRequestVO);
        });
        return result;
    }

    @Override
    public List<MyFriendsVO> operFriendRequest(String acceptUserId, String sendUserId, Integer operType) {

        QueryWrapper<FriendsRequest> query = new QueryWrapper<>();
        friendsRequestService.remove(query);
        if(operType==1){
            MyFriends entity = new MyFriends();
            entity.setId(sid.nextShort());
            entity.setMyUserId(acceptUserId);
            entity.setMyFriendUserId(sendUserId);
            myFriendsService.save(entity);

            MyFriends entity2 = new MyFriends();
            entity2.setId(sid.nextShort());
            entity2.setMyUserId(sendUserId);
            entity2.setMyFriendUserId(acceptUserId);
            myFriendsService.save(entity2);

            //使用ws主动推送消息到请求发起者更新他的列表为最新
            DataContent dataContent = new DataContent();
            dataContent.setAction(MsgActionEnum.PULL_FRIEND.type);
            Channel channel = UserChannelRel.get(sendUserId);
            if(channel!=null){
                channel.writeAndFlush(new TextWebSocketFrame(JsonUtils.objectToJson(dataContent)));
            }
        }

        QueryWrapper<MyFriends> queryMyFriend = new QueryWrapper<>();
        queryMyFriend.eq(MyFriends.MY_USER_ID,acceptUserId);
        List<MyFriends> list = myFriendsService.list(queryMyFriend);

        List<MyFriendsVO> result = new ArrayList<>();
        list.forEach(item->{
            Users sender = this.getById(item.getMyFriendUserId());
            MyFriendsVO friendRequestVO = new MyFriendsVO();
            friendRequestVO.setFriendFaceImage(sender.getFaceImage());
            friendRequestVO.setFriendUsername(sender.getUsername());
            friendRequestVO.setFriendUserId(sender.getId());
            friendRequestVO.setFriendNickname(sender.getNickname());
            result.add(friendRequestVO);
        });

        return result;
    }

    @Override
    public List<MyFriendsVO> myFriends(String userId) {
        QueryWrapper<MyFriends> queryMyFriend = new QueryWrapper<>();
        queryMyFriend.eq(MyFriends.MY_USER_ID,userId);
        List<MyFriends> list = myFriendsService.list(queryMyFriend);

        List<MyFriendsVO> result = new ArrayList<>();
        list.forEach(item->{
            Users sender = this.getById(item.getMyFriendUserId());
            MyFriendsVO friendRequestVO = new MyFriendsVO();
            friendRequestVO.setFriendFaceImage(sender.getFaceImage());
            friendRequestVO.setFriendUsername(sender.getUsername());
            friendRequestVO.setFriendUserId(sender.getId());
            friendRequestVO.setFriendNickname(sender.getNickname());
            result.add(friendRequestVO);
        });

        return result;
    }

    @Override
    public String saveMsg(ChatMsg chatMsg) {
        chatMsg.setCreateTime(new Date());
        chatMsg.setId(sid.nextShort());
        chatMsgService.save(chatMsg);
        return chatMsg.getId();
    }

    @Override
    public void singed(List<String> list) {
        list.forEach(item->{
            ChatMsg update = new ChatMsg();
            update.setId(item);
            update.setSingFlag(1);
            chatMsgService.updateById(update);
        });
    }

    @Override
    public List<ChatMsgs> listMsg(String sendId) {

        QueryWrapper<ChatMsg> query = new QueryWrapper<>();
        query.eq(ChatMsg.ACCEPT_USER_ID,sendId);
        query.eq(ChatMsg.SING_FLAG,0);
        List<ChatMsg> list = chatMsgService.list(query);

        List<ChatMsgs> chatMsgs = new ArrayList<>();

        list.forEach(item->{
            ChatMsgs chatMsgs1 = new ChatMsgs();
            chatMsgs1.setMsgId(item.getId());
            chatMsgs1.setMsg(item.getMsg());
            chatMsgs1.setReceiverId(item.getAcceptUserId());
            chatMsgs1.setSenderId(item.getSendUserId());
            chatMsgs.add(chatMsgs1);
        });



        return chatMsgs;
    }
}
